import React, { Component } from 'react';
import { Card, Table, Button, Icon, Modal } from 'antd';
import { ArrowRightOutlined } from '@ant-design/icons';
import LinkButton from '../../components/link-button';
import SaveForm from './save-form';
import { v4 as uuidv4 } from 'uuid';

let allData = [{
    "_id": {
      "$oid": "5e12b8bce31bb727e4b0e348"
    },
    "parentId": "0",
    "name": "家用电器",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e130e60e31bb727e4b0e34b"
    },
    "parentId": "0",
    "name": "手机",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e130ec7e31bb727e4b0e34c"
    },
    "parentId": "0",
    "name": "洗衣机",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e1346533ed02518b4db0cd7"
    },
    "parentId": "0",
    "name": "图书",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e13467e3ed02518b4db0cd8"
    },
    "parentId": "0",
    "name": "杯具",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e1346c83ed02518b4db0cd9"
    },
    "parentId": "0",
    "name": "纸",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e144dc7297c1138787e96ab"
    },
    "parentId": "0",
    "name": "服装",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e144de1297c1138787e96ac"
    },
    "parentId": "0",
    "name": "玩具",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e16e37e49dc6b38d018fe28"
    },
    "parentId": "0",
    "name": "手机",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e16e38949dc6b38d018fe29"
    },
    "name": "三星",
    "__v": 0,
    "parentId": "0"
  },{
    "_id": {
      "$oid": "5fc0bf33eb957f1b94f4a959"
    },
    "parentId": "0",
    "name": "医药",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc0bfa4eb957f1b94f4a95a"
    },
    "parentId": "0",
    "name": "食品",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc0bfcdeb957f1b94f4a95b"
    },
    "parentId": "0",
    "name": "发型",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc0bfd7eb957f1b94f4a95c"
    },
    "parentId": "0",
    "name": "水果",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc0bfdeeb957f1b94f4a95d"
    },
    "parentId": "0",
    "name": "发饰",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc0bfe6eb957f1b94f4a95e"
    },
    "parentId": "0",
    "name": "图纸",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a1833fe4221c4546275"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "冰箱",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a4133fe4221c4546276"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "微波炉",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a4a33fe4221c4546277"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "电饭煲",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a5133fe4221c4546278"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "洗衣机",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a6533fe4221c4546279"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "消毒碗柜",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a6f33fe4221c454627a"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "电视",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a7a33fe4221c454627b"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "抽油烟机",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc5a5ff4870c82a702c5efd"
    },
    "parentId": "0",
    "name": "bbb",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc5b24b4870c82a702c5f05"
    },
    "parentId": "0",
    "name": "2",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc5b2ae4870c82a702c5f06"
    },
    "parentId": "0",
    "name": "34",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc5b2b84870c82a702c5f07"
    },
    "parentId": "5fc5b2ae4870c82a702c5f06",
    "name": "222",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc74b650dd9b10798413162"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "电脑",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc9e7cc618171388c09b7eb"
    },
    "parentId": "0",
    "name": "哈哈哈",
    "__v": 0
  }];

allData.forEach(v => v['_id'] = v['_id']['$oid']);

// 一级列表所有数据  
let dataSource = allData.filter(v => v.parentId === '0');  


/**
 * 品类管理
 */
class Category extends Component {
    
    state = {
        loading: false,
        // 一级分类列表
        categorys: [],
        // 二级分类列表
        subCategorys: [],
        // 当前需要显示的分类列表的parentId
        parentId: '0',
        // 当前需要显示的分类列表的父级名称
        parentName: '',
        // 是否显示弹窗
        visible: false,
        // 弹窗标题
        modalTitle: '',
        // 保存时品类对象
        category: {}
    };
    
    /**
     * 初始化列
     */
    initColumns = () => {
        this.columns = [
            {
              title: '分类名称',
              // 指定显示数据的属性名
              dataIndex: 'name',
            },
            {
                title: '操作',
                width: 300,
                // 返回需要显示的界面
                render: (row) => (
                    <span>
                        <LinkButton onClick={() => this.handleUpdate('update', row) } >修改分类</LinkButton>
                        {/* null在这里不做任何显示，可以也可以用 && */}
                        { this.state.parentId === '0' ? 
                        <LinkButton onClick={() => this.showSubCategorys(row)}>查看子分类</LinkButton> : null}
                    </span>
                ),
            }
        ];
    }
    

    /**
     * 获取一级/二级列表数据
     */
    getCategorys = () => {
        this.setState({
            loading: true,
            // 剔除加载动画出现时，数据依然是显示的 问题
            categorys: [],
            subCategorys: []
        },() => {
            const { parentId } = this.state;
            setTimeout(() => {
                if(parentId === '0'){
                    this.setState({
                      categorys:  allData.filter(v => v.parentId === '0')
                    });
                }else{
                    this.setState({
                        // 匹配对应父级id的子级数据
                        subCategorys: allData.filter(v => v.parentId === parentId),
                    });
                }
                this.setState({ loading: false });
            }, 1000);
        });
    }

    /**
     * 显示二级列表数据界面
     */
    showSubCategorys = (row) => {
        // 该方法为异步操作，故在回调中调用getCategorys方法
        this.setState({
            parentId: row['_id'],
            parentName: row.name
        }, () => {
            console.log('parentId:', this.state.parentId);
            // 去获取二级
            this.getCategorys();
        });
    }

    
    /**
     * 显示一级列表数据界面
     */
    showCategory = () => {
        this.setState({
            parentId: '0'
        },() => {
            this.getCategorys();
        });
    }


    /**
     * 更新分类
     */
    handleUpdate = (type, row) => {
        this.setState({
          modalTitle: type === 'add' ? '添加分类' : '修改分类',
          category: row,
          visible: true
        });
    }
    
    
    /**
     * 保存分类
     */
    handleOk = () => {
      const { modalTitle, category } = this.state;
      if(modalTitle === '修改分类'){
        const name = this.form.current.getFieldValue('name');
        allData.forEach(v => {
          if(v['_id'] === category['_id']){
            v.name = name;
          }
        });
      }else{
        const parentId = this.form.current.getFieldValue('parentId');
        const name = this.form.current.getFieldValue('name');
        allData.unshift({
          "__v": 0,
          parentId,
          name,
          id: uuidv4()
        });
      }

      this.setState({
        visible: false
      },() => {
        // 清除表单数据
        this.form.current.resetFields();
        this.getCategorys();
      });
    }


    UNSAFE_componentWillMount(){
        this.initColumns();
    }

    
    componentDidMount(){
        // 发异步请求
        this.getCategorys();
    }

    render() { 
        // 获取一级列表状态数据
        const { 
            loading, 
            categorys, 
            parentId, 
            parentName, 
            subCategorys, 
            visible,
            modalTitle,
            category
        } = this.state;

        const categoryParam = category || {};
       
        // 小标题
        const title = parentId === '0' ? '一级分类列表' : (
            <span style={{ color: '#333' }}>
                <LinkButton onClick={this.showCategory}>一级分类列表</LinkButton>
                {/* <Icon type="arrow-right" /> */}
                <ArrowRightOutlined style={{marginRight: '5px'}} />
                <span>{parentName}</span>
            </span>
        );
        const extra = (
            <Button type="primary" onClick={() => this.handleUpdate('add')} >
                <Icon type="plus" />
                添加
            </Button>
        );

        return ( 
            <>
            <Card title={title} extra={extra}>
                <Table 
                loading={loading}
                bordered
                rowKey="_id"
                dataSource={parentId === '0' ? categorys : subCategorys} 
                columns={this.columns} 
                pagination={{ defaultPageSize: 5, showQuickJumper: true, }}
                />
            </Card> 
            <Modal 
            title={modalTitle} 
            visible={visible} 
            onOk={this.handleOk} 
            onCancel={() => this.setState({visible: false})}
            >
              <SaveForm 
              type={modalTitle === '添加分类' ? 'add': 'update'} 
              category={categoryParam}
              categorys={allData.filter(v => v.parentId === '0')}
              parentId={parentId}
              // 父传子 传递函数
              setForm={(form) => {this.form = form}}
              />
            </Modal>
            </>
        );
    }
}
 
export default Category;